package com.rookie.jeesdp.utils;

import com.rookie.jeesdp.entity.admin.LoginUser;
import com.rookie.jeesdp.entity.admin.Role;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Set;

public class UserUtils {

    public static LoginUser getLoginUser() {
        OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        return JsonUtils.toObject(JsonUtils.toJson(authentication.getUserAuthentication().getDetails()), LoginUser.class);
    }

    @SuppressWarnings("unchecked")
    public static boolean hasPermission(String permission) {
        LoginUser loginUser = getLoginUser();
        Set<Role> authorities = (Set<Role>) loginUser.getAuthorities();
        for (Role role : authorities) {
            if (permission.contains(":")) {
                StringBuilder s = new StringBuilder();
                String[] strs = permission.split(":");
                for (String str : strs) {
                    if (s.toString().isEmpty()) {
                        s.append(str);
                    }
                    if (role.getAuthority().equals(s.toString())) {
                        return true;
                    } else {
                        s.append(":").append(str);
                    }
                }
            } else {
                return loginUser.getPermissions().contains(permission);
            }
        }
        return false;
    }
}
